/**
 * 
 */
package com.laozhao.dreamframe.dbmanager;

import java.io.File;
import java.util.HashMap;
import java.util.NoSuchElementException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.laozhao.dreamframe.util.ToolsUtil;

/**
 * @author LaoZhao
 * 
 */
public class DBFactory {

	private transient Log log = LogFactory.getLog(this.getClass());

	private static DataSource localDataSource = null;
	private static HashMap<String, DataBaseManager> dBMagrMap = new HashMap<String, DataBaseManager>();

	// public DataBaseManager dataBaseManager;

	/**
	 * 
	 * @param dataSource
	 */
	public DBFactory(DataSource dataSource) {
		createInstance(dataSource);
	}

	/**
	 * 工厂销售
	 * 
	 * @param dataSource
	 * @return
	 */
	public static DataBaseManager getInstance(DataSource dataSource) {
		if (dBMagrMap.containsKey(dataSource.getSourceNameValue())) {
			return dBMagrMap.get(dataSource.getSourceNameValue());
		} else {
			return createInstance(dataSource);
		}
		// if(localDataSource == dataSource &&
		// dBMagrMap.get(dataSource.getSourceNameValue()) != null){
		// return dBMagrMap.get(dataSource.getSourceNameValue());
		// }else{
		// return createInstance(dataSource);
		// }
	}

	/**
	 * 工厂销售
	 * 
	 * @param dataSource
	 * @return
	 */
	public static DataBaseManager getInstance() {
		if (localDataSource == null) {
			File file; 
			file = new File(ToolsUtil.getRoot()
					+ "\\conf\\data_sources.xml");
			if (!file.exists()) {
				file = new File(ToolsUtil.getRoot()
						+ "\\data_sources.xml");
			}
			if (!file.exists()) {
				return null;
			}else {
				try {
					localDataSource = new DataSource(file);
					return getInstance(localDataSource);
				} catch (Exception e) {
					return null;
				}
			}
		}else {
			return getInstance(localDataSource);
		}
	}

	/**
	 * 工厂清仓处理 如果dataSource为空，则全部清空
	 * 
	 * @param dataSource
	 */
	public static synchronized void remove(DataSource dataSource) {
		if (dataSource != null) {
			dBMagrMap.remove(dataSource.getSourceNameValue());
		} else {
			dBMagrMap.clear();
		}
	}

	/**
	 * 工厂生产存货
	 * 
	 * @param DataSourceName
	 * @return
	 * @throws NoSuchElementException
	 */
	private static synchronized DataBaseManager createInstance(
			DataSource dataSource) throws NoSuchElementException {

		DataBaseManager dbmgr;
		try {
			dbmgr = new DataBaseManager(dataSource.getSourceDbTypeNameValue(),
					dataSource.getUrlValue(), dataSource.getUsrValue(),
					dataSource.getPwdValue(), dataSource.getServerNameValue());

			dBMagrMap.put(dataSource.getSourceNameValue(), dbmgr);
			return dbmgr;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
